﻿using System;
using System.IO;

namespace Comdiv.QWeb.Renders {
	public class FileRender : IRender {
		#region IRender Members

		public bool NeedResult {
			get { return true; }
		}

		public void Render(QWebContext context) {
			var filename = context.ActionResult as string;
			if (null == filename) throw new Exception("file is null");
			if (!File.Exists(filename)) throw new Exception("file not existed " + filename);
			context.ContentType = resoleMimeType(Path.GetExtension(filename).Substring(1));
			if (context.ContentType == "application/bin") {
				context.WriteOutFile(filename);
			}
			else {
				context.Output.Write(File.ReadAllText(filename));
			}
		}

		public void RenderError(Exception error, QWebContext context) {
			context.ContentType = "text/plain";
			context.Output.Write(error.ToString());
		}

		#endregion

		private string resoleMimeType(string ext) {
			switch (ext) {
				case "css":
					return "text/css";
				case "js":
					return "text/javascript";
				case "txt":
					return "text/plain";
				default:
					return "application/bin";
			}
		}
	}
}